package com.chen.palmar.project.producer;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.datasource.CommentRequest;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.dialog.ShareDialog;
import com.chen.palmar.common.widget.view.AutoTabLayout;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.entity.CollectEntity;
import com.chen.palmar.entity.ProducerInfoEntity;
import com.primb.androidlibs.net.exception.ApiException;
import com.squareup.picasso.Picasso;

import java.util.HashMap;

import butterknife.Bind;
import me.wangyuwei.flipshare.FlipShareView;
import me.wangyuwei.flipshare.ShareItem;
import rx.Subscription;

/**
 * Created by chen on 2018/1/4.
 */

public class ProducerDetailActivity extends BaseActivity {

    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.iv_top)
    ImageView ivTop;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.iv_producer_head)
    CircleImageView ivProducerHead;
    @Bind(R.id.tv_producer_name)
    TextView tvProducerName;
    @Bind(R.id.tab_detail)
    AutoTabLayout tabDetail;
    @Bind(R.id.fy_producer_detail)
    FrameLayout fyProducerDetail;
    private StoreInfoFragment storeInfoFragment;
    private BaseInfoFragment baseInfoFragment;
    private HouseInfoFragment houseInfoFragment;
    private FragmentManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {

        toolBar.setNavigationOnClickListener(v -> ProducerDetailActivity.this.finish());
        titleBar.setText("");

        ivTop.setVisibility(View.VISIBLE);
        ivTop.setImageResource(R.mipmap.edit_icon);
        ivTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(getIntent().getStringExtra("info"))) {
                    showPop(getIntent().getStringExtra("info"));
                }
            }
        });
        ivTop.setTag(false);

        manager = getSupportFragmentManager();
        setChoiceItem(0);

        tabDetail.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setChoiceItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        try {
            getDataForWeb(getIntent().getStringExtra("info"));
        } catch (Exception e) {
            e.printStackTrace();
            showToast("服务器数据出错，请稍后重试");
        }
    }

    private void setChoiceItem(int position) {
        FragmentTransaction transaction = manager.beginTransaction();
        hideFragments(transaction);
        Bundle bundle = new Bundle();
        bundle.putString("info", getIntent().getStringExtra("info"));
        switch (position) {
            case 0:
                if (storeInfoFragment == null) {
                    storeInfoFragment = new StoreInfoFragment();
                    storeInfoFragment.setArguments(bundle);
                    transaction.add(R.id.fy_producer_detail, storeInfoFragment).show(storeInfoFragment);
                } else {
                    transaction.show(storeInfoFragment);
                }
                break;
            case 1:
                if (baseInfoFragment == null) {
                    baseInfoFragment = new BaseInfoFragment();
                    baseInfoFragment.setArguments(bundle);
                    transaction.add(R.id.fy_producer_detail, baseInfoFragment).show(baseInfoFragment);
                } else {
                    transaction.show(baseInfoFragment);
                }
                break;
            case 2:
                if (houseInfoFragment == null) {
                    houseInfoFragment = new HouseInfoFragment();
                    houseInfoFragment.setArguments(bundle);
                    transaction.add(R.id.fy_producer_detail, houseInfoFragment).show(houseInfoFragment);
                } else {
                    transaction.show(houseInfoFragment);
                }
                break;
        }
        transaction.commit();
    }

    // 隐藏所有的Fragment,避免fragment混乱
    private void hideFragments(FragmentTransaction transaction) {
        if (storeInfoFragment != null) {
            transaction.hide(storeInfoFragment);
        }
        if (baseInfoFragment != null) {
            transaction.hide(baseInfoFragment);
        }
        if (houseInfoFragment != null) {
            transaction.hide(houseInfoFragment);
        }
    }

    private void getDataForWeb(String info) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("factoryId", info);
        Subscription subscribe = DataCenter.listProducerInfo(map).subscribe(new HttpSubscriber<ProducerInfoEntity>(this, showLoading()) {
            @Override
            public void onNext(ProducerInfoEntity producerInfoEntity) {
                ProducerInfoEntity.DataBean data = producerInfoEntity.getData();
                if (!TextUtils.isEmpty(data.getLogo())) {
                    Picasso.with(ProducerDetailActivity.this).load(data.getLogo()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(ivProducerHead);
                }
                tvProducerName.setText(data.getName());
                ivTop.setTag(data.getFavoriteStatus() == 1);
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_producer_detail;
    }

    private void showPop(String distrId) {
        int color = ContextCompat.getColor(this, R.color.app_font);
        FlipShareView share = new FlipShareView.Builder(this, ivTop).addItem(new ShareItem("收藏", color, Color.WHITE)).addItem(new ShareItem("分享", color, Color.WHITE)).setBackgroundColor(0x60000000).setItemDuration(500).setSeparateLineColor(ContextCompat.getColor(this, R.color.app_main_gray)).setAnimType(FlipShareView.TYPE_SLIDE).create();
        share.setOnFlipClickListener(new FlipShareView.OnFlipClickListener() {
            @Override
            public void onItemClick(int position) {
                if (position == 0) {
                    collectInfo(((boolean) ivTop.getTag()), distrId);
                } else if (position == 1) {
                    share(distrId);
                }
            }

            @Override
            public void dismiss() {

            }
        });
    }

    private void share(String info) {
        ShareDialog shareDialog = new ShareDialog();
        shareDialog.setRef_id(info);
        shareDialog.setRef_type("4");
        shareDialog.show(getSupportFragmentManager());
    }


    /**
     * 收藏
     *
     * @param tag
     */
    private void collectInfo(boolean tag, String id) {
        CommentRequest.collectInfo(id, "4", tag, new CommentRequest.OnLoadSuccessListener<CollectEntity>() {
            @Override
            public void onSuccess(CollectEntity entity) {
                if (!TextUtils.isEmpty(entity.getMessage())) {
                    showToast(entity.getMessage());
                    ivTop.setTag(!tag);
                }
            }

            @Override
            public void onFailure(ApiException e) {
                if ("已收藏，请勿重复收藏".equals(e.getMessage())) {
                    ivTop.setTag(!tag);
                }
            }
        });
    }

}
